package com.yylending.las.lending.process.chooseamount;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.Global;
import com.yylending.las.R;
import com.yylending.las.StatIDSet;
import com.yylending.las.base.BaseFragment;
import com.yylending.las.common.utils.AmountUtils;
import com.yylending.las.common.utils.FormatUtils;
import com.yylending.las.lending.process.ProcessActivity;
import com.yylending.las.lending.process.confirmloan.ConfirmLoanFragment;
import com.yylending.las.lending.quota.myquota.MyQuotaModel;
import com.yylending.las.personal.bandcard.BoundBankCards;

import java.util.List;

public class ChooseAmountFragment extends BaseFragment implements ChooseAmountPresenter.View {

	private static final String TAG = ChooseAmountPresenter.class.getSimpleName();
	private static final int LOADER_ID_CHOOSE_AMOUNT = 100;
	private static final int MIN_LOAN_AMOUNT = 50000;
	private static final int MEDIUM_LOAN_AMOUNT = 200000;
	private static final int MIN_SCALE_BASE = 1000;
	private static final int MEDIUM_SCALE_BASE = 2000;
	private static final int BIG_SCALE_BASE = 5000;
	/**
	 * 选择金额
	 */
	@BindView(R.id.choose_amount_tv)
	TextView mChooseAmountTv;
	/**
	 * 单选钮组
	 */
	@BindView(R.id.loan_periods_RadioG)
	RadioGroup mLoanPeriodsRG;
	/**
	 * 综合费用
	 */
	@BindView(R.id.comprehensive_costs_tv)
	TextView mComprehensiveCostsTv;
	/**
	 * 每期应还
	 */
	@BindView(R.id.terminally_repayment_tv)
	TextView mTerminallyRepaymentTv;

	/**
	 * 选择的借款额度
	 */
	int mSelectedAmount, mRealAmount;
	/**
	 * 最大可借额度
	 */
	int mMaxAmount;
	/**
	 * 借款期数
	 */
	int mSelectedLoanPeriods = 12;
	@BindView(R.id.bank_card_num_tv)
	TextView mBankCardNumTv;
	@BindView(R.id.bank_name_tv)
	TextView mBankNameTv;
	@BindView(R.id.choose_amount_change_hint)
	TextView mChooseAmountChangeHint;
	@BindView(R.id.term_twelve_RadioBtn)
	RadioButton mTermTwelveRadioBtn;
	@BindView(R.id.term_twenty_four_RadioBtn)
	RadioButton mTermTwentyFourRadioBtn;
	@BindView(R.id.term_thirty_six_RadioBtn)
	RadioButton mTermThirtySixRadioBtn;
	/**
	 * 利率对象
	 */
	private ChooseAmountModel.Rate mRate;
	private Unbinder mUnbinder;
	private ChooseAmountPresenter mPresenter;

	private MyQuotaModel.ApplyStatus mStatus;

	public static BaseFragment newInstance() {
		BaseFragment fragment = new ChooseAmountFragment();
		return fragment;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_choose_sum, null);
		mUnbinder = ButterKnife.bind(this, view);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		getActivity().getSupportLoaderManager().initLoader(LOADER_ID_CHOOSE_AMOUNT, null, this);
		mStatus = getActivity().getIntent().getParcelableExtra(ProcessActivity.ARG_APPLY_STATUS);
		mSelectedAmount = Integer.valueOf(mStatus.quota.ts);
		judgeAmount();
		mMaxAmount = mSelectedAmount;

		// 如果某个期限的额度小于5w则不显示该期限
		if (Integer.valueOf(mStatus.quota.tl) < Global.mMinOnlineQuota) {
			mTermTwelveRadioBtn.setVisibility(View.INVISIBLE);
		}
		if (Integer.valueOf(mStatus.quota.tf) < Global.mMinOnlineQuota) {
			mTermTwentyFourRadioBtn.setVisibility(View.INVISIBLE);
		}
		if (Integer.valueOf(mStatus.quota.ts) < Global.mMinOnlineQuota) {
			mTermThirtySixRadioBtn.setVisibility(View.INVISIBLE);
		}

		mSelectedLoanPeriods = 36;
		mChooseAmountTv.setText(FormatUtils.getDecoratedAmountWithSymbol(mSelectedAmount));
		updateData();
		mLoanPeriodsRG.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
					case R.id.term_twelve_RadioBtn:
						mSelectedLoanPeriods = 12;
						mSelectedAmount = Integer.valueOf(mStatus.quota.tl);
						judgeAmount();
						if(mSelectedAmount < mMaxAmount && View.VISIBLE != mChooseAmountChangeHint.getVisibility()){
							mChooseAmountChangeHint.setVisibility(View.VISIBLE);
						}
						break;
					case R.id.term_twenty_four_RadioBtn:
						mSelectedLoanPeriods = 24;
						mSelectedAmount = Integer.valueOf(mStatus.quota.tf);
						judgeAmount();
						if(mSelectedAmount < mMaxAmount && View.VISIBLE != mChooseAmountChangeHint.getVisibility()){
							mChooseAmountChangeHint.setVisibility(View.VISIBLE);
						}
						break;
					case R.id.term_thirty_six_RadioBtn:
						mSelectedLoanPeriods = 36;
						mSelectedAmount = Integer.valueOf(mStatus.quota.ts);
						judgeAmount();
						break;
				}
				mChooseAmountTv.setText(FormatUtils.getDecoratedAmountWithSymbol(mSelectedAmount));
				updateData();
			}

		});

		Intent intent = getActivity().getIntent();
		List<BoundBankCards.BankInfo> bankList = intent.getParcelableArrayListExtra(ProcessActivity.BANK_INFO);
		BoundBankCards.BankInfo bankInfo = bankList.get(0);
		mBankNameTv.setText(bankInfo.getBankName());
		mBankCardNumTv.setText(getString(R.string.bank_card_last_four_num, bankInfo.getNumber().substring(bankInfo.getNumber().length() - 4)));
	}

	private void judgeAmount(){
		mRealAmount = mSelectedAmount;
		if(mSelectedAmount > Global.mMaxOnlineQuota){
			mSelectedAmount = Global.mMaxOnlineQuota;
		}
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
		mUnbinder.unbind();
		getActivity().getSupportLoaderManager().destroyLoader(LOADER_ID_CHOOSE_AMOUNT);
	}

	private void updateData() {
		if (null != mRate) {
			String comprehensiveCost = AmountUtils.getComprehensiveCost(mSelectedAmount, mRate.onceFeeRate);
			//String amountActualToAccount = AmountUtils.getActualToAccount(mSelectedAmount, comprehensiveCost);
			String terminallyRepayment = AmountUtils.getTerminallyRepayment(mRate, mSelectedAmount, mSelectedLoanPeriods);
			mComprehensiveCostsTv.setText(FormatUtils.getAmountWithSymbol(comprehensiveCost));
			mTerminallyRepaymentTv.setText(FormatUtils.getAmountWithSymbol(terminallyRepayment));
		}
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		if (null == mPresenter) {
			mPresenter = (ChooseAmountPresenter) data;
			mPresenter.attach(this);
			mPresenter.getRate();
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		return new PresenterLoader<>(getActivity(), new ChooseAmountPresenter.Generator());
	}

	@OnClick(R.id.next_btn)
	public void onClick(View v) {
		if (null == mRate) {
			mPresenter.getRate();
			return;
		}

		ProcessActivity activity = (ProcessActivity) getActivity();
		setProcess();
		if (null != activity.mConfirmLoadFragment) {
			//返回重新选择借款金额和期数，重置数据，并刷新借款确认页数据
			EventAgent.post(new ConfirmLoanFragment.ConfirmLoadBean());
		}
		StatService.onEventWithSingleAttribute(getContext(), StatIDSet.EVENT_ID_CONFIRM_AMOUNT_AND_PERIODS, ProcessActivity.mProcess.loanTerm);
		activity.pageDown();
	}

	/**
	 * 保存借款金额、借钱期数、每月应还、实际借款金额
	 */
	private void setProcess() {
		ProcessActivity.mProcess.businessSum = String.valueOf(mSelectedAmount);
		ProcessActivity.mProcess.loanTerm = String.valueOf(mSelectedLoanPeriods);
		ProcessActivity.mProcess.terminallyRepayment = mTerminallyRepaymentTv.getText().toString();
		ProcessActivity.mProcess.realBusinessSum = String.valueOf(mRealAmount);
	}

	@Override
	public void getRateSuccess(ChooseAmountModel.Rate rate) {
		mRate = rate;
		updateData();
	}

	@Override
	public void getRateFailure(String tips) {
		showToast(tips);
	}

	@Override
	public void onFunctionalCompleted(boolean autoTips) {
		super.onFunctionalCompleted(autoTips);
		dismissLoading();
	}
}
